package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class JwtFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //响应消息
        ServerHttpResponse response = exchange.getResponse();

        //请求消息
        ServerHttpRequest request = exchange.getRequest();

        HttpHeaders headers = response.getHeaders();

        //判断他是否为登录请求
        if (request.getURI().getPath().contains("/admin/login")){
            //放行
            return chain.filter(exchange);
        }

        String token = headers.getFirst("token");


        //判断Jwt令牌是否为空
        if (StringUtils.isEmpty("token")){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拒绝
            response.setComplete();
            }
        try {
        //调用Jwt工具
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拒绝
            response.setComplete();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 3;
    }
}
